package com.fast.admin.controller.common;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.fast.framework.config.redis.RedisCache;
import com.fast.framework.constant.CacheConstants;
import com.fast.framework.constant.Constants;
import com.fast.framework.core.AjaxResult;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.ConnectException;
import java.util.concurrent.TimeUnit;

/**
 * 验证码操作处理
 *
 * @author lanyuankeji
 */
@Api(tags = "图形验证码API")
@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    private static final Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @Resource
    private DefaultKaptcha defaultKaptcha;
    @Resource
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
    @ApiOperation(value = "验证码")
    @GetMapping("/getCaptcha")
    public AjaxResult getCaptcha() {
        AjaxResult ajax = AjaxResult.success();

        //redis存储的值
        String uuid = StrUtil.uuid();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();

        try {
            // 生成验证码
            String capStr = generateCaptcha();
            //测试完毕删除
            ajax.put("code", capStr);
            redisCache.setCacheObject(verifyKey, capStr, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);

            logger.info("redis存储的验证码key: " + verifyKey);
            logger.info("redis存储的验证码value: " + capStr);
            logger.info("redis存储的验证码到期时间 " + TimeUnit.MINUTES);

            //根据内容输出为图片
            BufferedImage image = generateCaptchaImage(capStr);
            ImageIO.write(image, "jpg", os);
        } catch (Exception e) {
            if (e instanceof ConnectException) {
                throw new RuntimeException("redis未开启");
            } else {
                return AjaxResult.error(e.getMessage());
            }
        }

        ajax.put("uuid", uuid);
        ajax.put("img", Base64.encode(os.toByteArray()));
        return ajax;
    }

    // 封装生成验证码的逻辑
    private String generateCaptcha() {
        return defaultKaptcha.createText();
    }

    // 封装生成验证码图片的逻辑
    private BufferedImage generateCaptchaImage(String captcha) {
        return defaultKaptcha.createImage(captcha);
    }
}
